<template>
	<div>
		<div class="container">
			<h2 style="text-align: center;">采购记录</h2>
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="doSearch">
					<!--					<a-form-item label="选择类型">-->
					<!--						<a-select v-model:value="searchState.type" style="width:200px" :show-search="true" placeholder="请选择类型" :options="typeOptions" option-filter-prop="label" @change="doSearch"></a-select>-->
					<!--					</a-form-item>-->
					<a-row :gutter="20">
						<a-col :span="24">
							<a-form-item label="选择类型">
								<a-radio-group v-model:value="searchState.type" @change="doSearch">
									<a-radio-button v-for="option of typeOptions" :key="option.value" :value="option.value">{{ option.label }}</a-radio-button>
								</a-radio-group>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="20">
						<a-col :span="8">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" allow-clear :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择供应商名称" name="supplier_id">
								<a-select v-model:value="searchState.supplier_id" :show-search="true" placeholder="请选择供应商" :options="userlist" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="申请人">
								<a-input v-model:value="searchState.applier_name" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="20">
						<a-col :span="12">
							<a-form-item label="时间范围">
								<a-range-picker v-model:value="searchState.date_range" allow-clear show-time value-format="YYYY-MM-DD HH:mm:ss" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<a-table :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="dataSource" :pagination="pagination" @change="handleChange">
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'ys_status'">
							<a-tag v-if="record.ys_status === 1" color="default">未验收</a-tag>
							<a-tag v-else-if="record.ys_status === 2 && record.ys_exceed === 0" color="green">正常验收</a-tag>
							<a-tag v-else color="red">超量验收</a-tag>
						</template>
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="60" type="link" @click="handleDetail(record)">
									<diff-outlined />查看
								</a-button>
							</a-space>
						</template>
					</template>
				</a-table>
			</div>

			<a-modal v-model:visible="visible" :footer="null" :width="1000" title="查看商砼申请">
				<a-form ref="formRef">
					<table cellspacing="0" cellpadding="0" style="width: 100%;">
						<tr>
							<td>
								<a-form-item label="项目名称" name="project_id">{{ shangtongInfo.project?.name }}</a-form-item>
							</td>
							<td>
								<a-form-item label="预计浇筑部位">{{ shangtongInfo.part }}</a-form-item>
							</td>
						</tr>
						<tr>
							<td>
								<a-form-item label="砼标号（类别）">{{ shangtongInfo.type }}</a-form-item>
							</td>
							<td>
								<a-form-item label="预计浇筑方量（m3）">{{ shangtongInfo.fangliang }}</a-form-item>
							</td>
						</tr>
						<tr>
							<td>
								<a-form-item label="是否泵送（长度）">{{ shangtongInfo.changdu }}</a-form-item>
							</td>
							<td>
								<a-form-item label="申请塌落度（mm）">{{ shangtongInfo.luodu }}</a-form-item>
							</td>
						</tr>
						<tr>
							<td>
								<a-form-item label="现场联系人">{{ shangtongInfo.luodu }}</a-form-item>
							</td>
							<td>
								<a-form-item label="现场联系电话">{{ shangtongInfo.tel }}</a-form-item>
							</td>
						</tr>
						<tr>
							<td colspan="2">
								<a-form-item label="预计浇筑日期">{{ shangtongInfo.add_time }}</a-form-item>
							</td>
						</tr>
						<tr>
							<td colspan="2">
								<a-form-item label="备注">{{ shangtongInfo.memo }}</a-form-item>
							</td>
						</tr>
					</table>
				</a-form>
			</a-modal>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import dayjs from "dayjs";
import { SearchOutlined, DiffOutlined } from "@ant-design/icons-vue";
import { post } from "../utils";
import router from "../router";
import { useRoute } from "vue-router";
const route = useRoute();
const query = route.query;


const typeOptions = [
	{
		value: "purchase",
		label: "物资周转料采购"
	},
	{
		value: "shangtong",
		label: "商砼采购"
	},
	{
		value: "machineapply",
		label: "机械租赁"
	},
	{
		value: "auxiliary",
		label: "辅助物料采购"
	},
];
const shipStatusList = [
	{
		value: 1,
		label: "待发货"
	},
	{
		value: 2,
		label: "已发货"
	}
];
const searchRef = ref();
const searchState = reactive({
	type: typeOptions[0].value
});
const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left"
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.name;
		}
	},
	{
		title: "供应商名称",
		dataIndex: "purchaseOrderMaterials",
		sorter: false,
		width: 200,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			const key = 'supplier'
			const arr = text.filter(item => key in item).map(item => item.supplier['company_name'])
			return [...new Set(arr)].join(',');
		}
	},
	{
		title: "申请人",
		dataIndex: "applier",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.fullname || text.username;
		}
	},
	{
		title: "采购类型",
		dataIndex: "type",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			const typeItem = typeOptions.find(item => item.value === text);
			return typeItem.label;
		}
	},
	{
		title: "采购单号",
		dataIndex: "code",
		sorter: false,
		ellipsis: true
	},
	{
		title: "采购人",
		dataIndex: "purchaser",
		sorter: false,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.fullname;
		}
	},
	{
		title: "创建时间",
		dataIndex: "create_time",
		sorter: false,
		ellipsis: true,
		width: 180,
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "状态",
		dataIndex: "ship_status",
		sorter: false,
		width: 100,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return shipStatusList.filter(item => item.value === text)[0]?.label || "未知状态";
		}
	},
	{
		title: "验收状态",
		dataIndex: "ys_status",
		sorter: false,
		width: 100,
		ellipsis: true,
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 120,
		align: "center"
	}
];
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const projectOptions = ref([]);
const companyOptions = ref([]);
const userlist = ref([]); //供应商列表
post("user", { is_supplier: 1, page_size: Infinity }).then(({ data }) => {
	userlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.company_name
		};
	});
});

const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24]),
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
})
const visible = ref(false);
const shangtongInfo = ref({});
const handleDetail = record => {
	router.push(`/purchase/order/info/${record.id}?type=${record.type}`);
};

const pagination = ref({
	total: 0,
	current: 1,
	pageSize: 10
});
const proxy = getCurrentInstance();
const dataSource = ref([]);
const getDataSource = async () => {
	if (!searchState.type) {
		proxy.$message.error("请选择采购类型");
		return;
	}
	const query = {};
	if (pagination.value.pageSize) {
		query['page_size'] = pagination.value.pageSize;
	}
	if (pagination.value.current) {
		query['page'] = pagination.value.current;
	}
	router.replace({ query: {
		...query,
		...searchState,
		start_time: searchState.date_range && searchState.date_range[0],
		end_time: searchState.date_range && searchState.date_range[1],
		type: searchState.type
	}})
	const search = {};
	if (searchState.company_id) {
		if (!projectOptions.value.length) await getProjects();
		search.project_ids = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		}).map(item => item.value).join(',');
		if (!search.project_ids) {
			return [];
		}
	}
	post("purchaseOrder", {
		...searchState,
		...search,
		start_time: searchState.date_range && searchState.date_range[0],
		end_time: searchState.date_range && searchState.date_range[1],
		page: pagination.value.current,
		page_size: pagination.value.pageSize
	}).then(({ data, total }) => {
		dataSource.value = (data || []).map(item => {
			item.type = searchState.type;
			const planInfo = item[`${item.type}ApplyPlan`];
			item.project = planInfo.project;
			item.applier = planInfo.applier || planInfo.purchaser;
			return item;
		});
		pagination.value.total = total;
	});
};
if (query) {
	if (query.type) searchState.type = query.type;
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.supplier_id) searchState.supplier_id = parseInt(query.supplier_id);
	if (query.code) searchState.code = query.code;
	if (query.applier_name) searchState.applier_name = query.applier_name;
	if (query.start_time && query.end_time) {
		searchState.date_range = [
			dayjs(query.start_time).format('YYYY-MM-DD HH:mm:ss'),
			dayjs(query.end_time).format('YYYY-MM-DD HH:mm:ss')
		];
	}
	if (query.page_size) {
		pagination.value.pageSize = parseInt(query.page_size);
	}
	if (query.page) {
		pagination.value.current = parseInt(query.page);
	}
	getDataSource();
}
const doSearch = () => {
	pagination.value.current = 1;
	getDataSource();
};

const handleChange = pg => {
	pagination.value.current = pg.current;
	pagination.value.pageSize = pg.pageSize;
	getDataSource();
};
doSearch();
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
